<template>
  <div class="color-debug">
    <h2>🔍 颜色调试页面</h2>
    
    <div class="debug-controls">
      <el-button @click="connect" :disabled="isConnected" type="primary">
        连接
      </el-button>
      <el-button @click="createRoom" :disabled="!isConnected" type="success">
        创建房间
      </el-button>
      <el-button @click="joinRoom" :disabled="!isConnected" type="warning">
        加入房间
      </el-button>
      <el-button @click="debugColors" type="info">
        调试颜色
      </el-button>
    </div>
    
    <div class="debug-info">
      <h3>调试信息</h3>
      <div class="info-item">
        <strong>连接状态:</strong> {{ isConnected ? '✅ 已连接' : '❌ 未连接' }}
      </div>
      <div class="info-item">
        <strong>房间ID:</strong> {{ roomId || '无' }}
      </div>
      <div class="info-item">
        <strong>当前玩家:</strong> {{ currentPlayer?.nickname || '无' }}
      </div>
      <div class="info-item">
        <strong>玩家数量:</strong> {{ players.length }}
      </div>
    </div>
    
    <div class="color-details" v-if="players.length > 0">
      <h3>颜色详情</h3>
      <div v-for="player in players" :key="player.id" class="player-detail">
        <div class="player-header">
          <span class="name">{{ player.nickname }}</span>
          <span v-if="player.isOwner" class="owner-badge">👑 房主</span>
        </div>
        <div class="color-info">
          <div class="color-item">
            <span class="label">AvatarColor:</span>
            <span class="value" :style="{ color: player.avatarColor }">{{ player.avatarColor || 'undefined' }}</span>
            <div class="color-preview" :style="{ backgroundColor: player.avatarColor }"></div>
          </div>
          <div class="color-item">
            <span class="label">BrushColor:</span>
            <span class="value" :style="{ color: player.brushColor }">{{ player.brushColor || 'undefined' }}</span>
            <div class="color-preview" :style="{ backgroundColor: player.brushColor }"></div>
          </div>
          <div class="color-item">
            <span class="label">兼容Color:</span>
            <span class="value" :style="{ color: player.color }">{{ player.color || 'undefined' }}</span>
            <div class="color-preview" :style="{ backgroundColor: player.color }"></div>
          </div>
        </div>
      </div>
    </div>
    
    <div class="debug-log">
      <h3>调试日志</h3>
      <div class="log-content">
        <div v-for="log in logs.slice(-20)" :key="log.id" class="log-item">
          <span class="timestamp">{{ log.timestamp }}</span>
          <span class="message">{{ log.message }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { createSignalRService } from '@/services/socketService'
import { useGameStore } from '@/stores/game'

const gameStore = useGameStore()
const isConnected = ref(false)
const roomId = ref('')
const currentPlayer = ref(null)
const players = ref([])
const logs = ref([])

const signalRService = createSignalRService(gameStore)

// 计算属性
const isConnectedComputed = computed(() => gameStore.isConnected)
const currentPlayerComputed = computed(() => gameStore.currentPlayer)
const playersComputed = computed(() => gameStore.players)

// 监听状态变化
watch(isConnectedComputed, (newValue) => {
  isConnected.value = newValue
  addLog(`连接状态变化: ${newValue ? '已连接' : '未连接'}`)
})

watch(currentPlayerComputed, (newValue) => {
  currentPlayer.value = newValue
  if (newValue) {
    addLog(`当前玩家更新: ${newValue.nickname} (头像: ${newValue.avatarColor}, 画笔: ${newValue.brushColor})`)
  }
})

watch(playersComputed, (newValue) => {
  players.value = newValue || []
  addLog(`玩家列表更新: ${newValue?.length || 0} 个玩家`)
  
  if (newValue && newValue.length > 0) {
    newValue.forEach((player, index) => {
      addLog(`玩家 ${index + 1}: ${player.nickname} - 头像: ${player.avatarColor}, 画笔: ${player.brushColor}`)
    })
  }
})

function addLog(message) {
  const timestamp = new Date().toLocaleTimeString()
  logs.value.push({
    id: Date.now() + Math.random(),
    timestamp,
    message
  })
  
  if (logs.value.length > 50) {
    logs.value.shift()
  }
}

async function connect() {
  try {
    addLog('尝试连接...')
    await signalRService.connect()
    addLog('连接成功')
  } catch (error) {
    addLog(`连接失败: ${error.message}`)
  }
}

async function createRoom() {
  try {
    const roomCode = 'debug-' + Math.random().toString(36).substr(2, 6)
    const playerId = 'player-' + Math.random().toString(36).substr(2, 9)
    
    addLog(`创建房间: ${roomCode}`)
    await signalRService.createRoom(roomCode, '调试房间', 6, '', playerId, '调试房主')
    roomId.value = roomCode
    addLog('房间创建成功')
  } catch (error) {
    addLog(`创建失败: ${error.message}`)
  }
}

async function joinRoom() {
  try {
    const playerId = 'player-' + Math.random().toString(36).substr(2, 9)
    const targetRoom = roomId.value || 'debug-room'
    
    addLog(`加入房间: ${targetRoom}`)
    await signalRService.joinRoom(targetRoom, playerId, '调试玩家')
    addLog('加入成功')
  } catch (error) {
    addLog(`加入失败: ${error.message}`)
  }
}

function debugColors() {
  addLog('=== 开始颜色调试 ===')
  
  if (players.value.length === 0) {
    addLog('❌ 没有玩家')
    return
  }
  
  players.value.forEach((player, index) => {
    addLog(`玩家 ${index + 1}: ${player.nickname}`)
    addLog(`  头像颜色: ${player.avatarColor || 'undefined'}`)
    addLog(`  画笔颜色: ${player.brushColor || 'undefined'}`)
    addLog(`  兼容颜色: ${player.color || 'undefined'}`)
  })
  
  // 检查颜色唯一性
  const avatarColors = players.value.map(p => p.avatarColor).filter(c => c)
  const brushColors = players.value.map(p => p.brushColor).filter(c => c)
  
  const uniqueAvatarColors = new Set(avatarColors)
  const uniqueBrushColors = new Set(brushColors)
  
  addLog(`头像颜色唯一性: ${avatarColors.length === uniqueAvatarColors.size ? '✅' : '❌'}`)
  addLog(`画笔颜色唯一性: ${brushColors.length === uniqueBrushColors.size ? '✅' : '❌'}`)
  
  if (avatarColors.length !== uniqueAvatarColors.size) {
    addLog(`❌ 重复的头像颜色: ${avatarColors.join(', ')}`)
  }
  
  if (brushColors.length !== uniqueBrushColors.size) {
    addLog(`❌ 重复的画笔颜色: ${brushColors.join(', ')}`)
  }
}

onMounted(() => {
  addLog('颜色调试页面加载完成')
})
</script>

<style scoped>
.color-debug {
  padding: 20px;
  max-width: 1000px;
  margin: 0 auto;
}

.debug-controls {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.debug-info {
  background: #f8f9fa;
  padding: 15px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.info-item {
  margin-bottom: 8px;
}

.color-details {
  margin-bottom: 20px;
}

.player-detail {
  border: 1px solid #ddd;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 10px;
  background: white;
}

.player-header {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
}

.name {
  font-weight: bold;
  font-size: 16px;
}

.owner-badge {
  background: #ffd700;
  color: #333;
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: bold;
}

.color-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.color-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

.label {
  font-weight: bold;
  min-width: 100px;
}

.value {
  font-family: monospace;
  min-width: 120px;
}

.color-preview {
  width: 30px;
  height: 20px;
  border-radius: 4px;
  border: 1px solid #ddd;
}

.debug-log {
  background: #2d3748;
  color: #e2e8f0;
  padding: 15px;
  border-radius: 8px;
  max-height: 400px;
  overflow-y: auto;
}

.log-content {
  font-family: monospace;
  font-size: 12px;
}

.log-item {
  margin-bottom: 5px;
  padding: 2px 0;
}

.timestamp {
  color: #a0aec0;
  margin-right: 10px;
}

.message {
  color: #e2e8f0;
}
</style>
